<?php

class Auth_LDAP {

    public function __construct($ldapHost) {
        $this->connect($ldapHost);
    }

    /*  connect(string $ldapHost)                           :   Connect to LDAP server
     *
     *  @access public
     *  @param  string  $ldapHost                           -   Hostname of the LDAP server
     */
    public function connect($ldapHost) {
        $this->ldapConn     =   ldap_connect("$ldapHost");

        ldap_set_option($this->ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);

        if(($ldapError = ldap_error($this->ldapConn)) !== "Success") {
            throw new Exception("Unable to connect to LDAP server [$ldapError]");
        }
    }

    /*  close()                                             :   Close off all resources to LDAP server
     *
     *  @access public
     */
    public function close() {
        if(isset($this->ldapBind) && is_resource($this->ldapBind)) {
            ldap_unbind($this->ldapBind);
        }

        ldap_close($this->ldapConn);
    }

    /*  bind(string $ldapLogin, string $ldapPassword)       :   Bind to the LDAP server
     *
     *  @access public
     *  @param  string  $ldapLogin                          -   Complete DN for the user
     *  @param  string  $ldapPassword                       -   User's password
     *  @return mixed                                       -   Returns results from ldap_error() if failure or TRUE on success
     */
    public function bind($ldapLogin, $ldapPassword) {
        if(($this->ldapBind = @ldap_bind($this->ldapConn, $ldapLogin, $ldapPassword)) === FALSE) {
            return ldap_error($this->ldapConn);
        } else {
            return TRUE;
        }
    }

    /*  verifyUser(string $username, string $password)      :   Verify the password against the LDAP server
     *
     *  @access public
     *  @param  string  $username                           -   The username of the end user
     *  @param  string  $password                           -   Password for the user
     *  @return mixed                                       -   Returns FALSE for complete failure, throw an Exception for failure, or TRUE on success
     */
    public function verifyUser($username, $password) {
        $config     =   Control::getConfigs();

        if(isset($config['auth']['ldap']['baseDN']) && !empty($config['auth']['ldap']['baseDN'])) {
            $ldapBase   =   $config['auth']['ldap']['baseDN'];

            if(($ldapBind = $this->bind("cn=$username,$ldapBase", $password)) !== TRUE) {
                switch($ldapBind) {
                    case "Invalid credentials":
                        return FALSE;
                    break;
                }
            } else {
                return TRUE;
            }
        } else {
            throw new Exception("Invalid configurations for LDAP authentication");
        }
    }

    public function __destruct() {
        $this->close();
    }
}
?>
